import 'package:flutter/material.dart';
import 'dart:ui' as ui;

typedef ScrawlPaintHandler = void Function(Canvas canvas, Size size);

class ScrawlPainter extends CustomPainter {
  final ScrawlPaintHandler paintHandler;
  final Rect displayRect;
  final ui.Image image;
  final Rect imageRect;

  ScrawlPainter(
    this.paintHandler, {
    this.displayRect,
    this.image,
    this.imageRect,
  });

  @override
  void paint(Canvas canvas, Size size) {
    canvas.saveLayer(Offset.zero & size, Paint()); // draw beging

    canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height));

    // 位移与裁剪
    if (displayRect is Rect) {
      canvas.translate(-displayRect.topLeft.dx, -displayRect.topLeft.dy);
      canvas.clipRect(displayRect);
    }
    // 图片层
    if (image is ui.Image && imageRect is Rect) {
      canvas.drawImageRect(
        image,
        Rect.fromLTWH(0, 0, image.width * 1.0, image.height * 1.0),
        imageRect,
        Paint(),
      );
      canvas.clipRect(imageRect);
    }

    // 绘制层
    paintHandler(canvas, size);

    canvas.restore(); // draw end
  }

  // todo
  @override
  bool shouldRepaint(ScrawlPainter other) => true;
}
